import 'pgearthBuild/Widgets/widgets.css'
import { FilterNullValue } from '@/utils/utils'

// baseMap ScreenSpaceEventHandler 事件
import ScreenSpaceEventHandler from 'pgearthSource/Core/ScreenSpaceEventHandler'
import ScreenSpaceEventType from 'pgearthSource/Core/ScreenSpaceEventType'

// initBaseMap
import SceneView from 'pgearthExtends/views/SceneView'
import SceneMode from "pgearthSource/Scene/SceneMode";
import BaseLayerControl from 'pgearthExtends/widgets/BaseLayerControl'
import EventDrive from 'pgearthExtends/others/EventDrive'

// XzqhLayer
import WMSLayer from 'pgearthExtends/layers/WMSLayer' //Xzqh
import WMTSLayer from 'pgearthExtends/layers/WMTSLayer'//路网

//point
import GraphicsLayer from 'pgearthExtends/layers/GraphicsLayer'
import Graphic from 'pgearthExtends/Graphic'
import PicStyleSymbol from 'pgearthExtends/symbols/PicStyleSymbol'
import NearFarScalar from 'pgearthSource/Core/NearFarScalar'
import VerticalOrigin from 'pgearthSource/Scene/VerticalOrigin'
import HeightReference from 'pgearthSource/Scene/HeightReference'
import when from 'pgearthSource/ThirdParty/when'

export default {
	// 初始化地图组件
	initBaseMap(id = 'main-map', vue) {
		this.vue = vue;
		this.viewer = new SceneView({
			container: id,
			baseMap: new WMTSLayer({    //天地图影像
					id: 'myLayer',
					url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=1d109683f4d84198e37a38c442d68311",
					title: 'tdt',
					tileMatrixSet: 'tdt1',
			}),
			scene3DOnly: false,
			sceneMode: SceneMode.SCENE2D,
		})
		this.map = this.viewer.map;
		
		setTimeout(()=>{
			BaseLayerControl.addLayer({
				viewer: this.viewer, 
				type: 'arcgis',
				url: 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer'
			})
		},100)
		
		uni.getLocation({
			type: 'wgs84',
			geocode: true,
			success: (res)=> {
				this.goView({
					longitude: res.longitude || 106.55,
					latitude: res.latitude || 29.57,
					height: 2000000
				});
			},
			fail: (res)=> {
				this.goView({
					longitude: 106.55,
					latitude: 29.57,
					height: 2000000
				});
			},
		});

		// let wmtsLayer = new WMTSLayer({
		// 	id: "liwang",
		// 	url: "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=1d109683f4d84198e37a38c442d68311",
		// 	title: "TileMatrix",
		// 	tileMatrixSet: "default028mm",
		// });
		// this.map.add(wmtsLayer);

		new ScreenSpaceEventHandler(this.viewer.canvas).setInputAction(click => {
				const pick = this.viewer.scene.pick(click.position)
				if (pick && pick.id) {
						pick.id.popupTemplate && pick.id.popupTemplate.actions()
				} else {
						// this.removeLayerById('foucsGraphicsLayer')
						this.viewer.popupTemplate.closePop()
				}
		}, ScreenSpaceEventType.LEFT_DOWN)

		new ScreenSpaceEventHandler(this.viewer.canvas).setInputAction(click => {
				const pick = this.viewer.scene.pick(click.endPosition)
				if (pick && pick.id && pick.id.popupTemplate) {
						// pick.id.popupTemplate && pick.id.popupTemplate.actions('textGraphics')
				} else {
						// this.removeLayerById('textGraphics')
				}
		}, ScreenSpaceEventType.MOUSE_MOVE)
		
		// new ScreenSpaceEventHandler(this.viewer.canvas).setInputAction((wheelment)=> {
		// 	let scale = this.viewer.pgEarthWidget.pgEarthNavigation.distanceLegendViewModel.distanceLabel;
		// 	let height = Number(scale.substring(0, scale.length-3));
		// 	if(height > 300){
		// 		this.aggregaGraphicsLayer2.show = false;
		// 		this.aggregaGraphicsLayer3.show = false;
		// 	}else if(height>100 && height<=300){
		// 		this.aggregaGraphicsLayer2.show = true;
		// 		this.aggregaGraphicsLayer3.show = false;
		// 	}else if(height>5 && height<=100){
		// 		this.aggregaGraphicsLayer2.show = false;
		// 		this.aggregaGraphicsLayer3.show = true;
		// 	}
		// }, ScreenSpaceEventType.WHEEL);
		 
		 this.viewer.camera.changed.addEventListener(()=> {
			 let scale = this.viewer.pgEarthWidget.pgEarthNavigation.distanceLegendViewModel.distanceLabel;
			 if(scale){
				 let height = Number(scale.substring(0, scale.length-3));
				 if(height > 300){
					this.aggregaGraphicsLayer1.show = true; 
				 	this.aggregaGraphicsLayer2.show = false;
				 	this.aggregaGraphicsLayer3.show = false;
				 }else if(height>50 && height<=300){
					this.aggregaGraphicsLayer1.show = false;  
				 	this.aggregaGraphicsLayer2.show = true;
				 	this.aggregaGraphicsLayer3.show = false;
				 }else if(height>5 && height<=50){
					this.aggregaGraphicsLayer1.show = false;
				 	this.aggregaGraphicsLayer2.show = false;
				 	this.aggregaGraphicsLayer3.show = true;
				 }
				 this.pointGraphicsLayer.show = true
			 }
		 })
		
		new EventDrive({
			viewer: this.viewer,
			eventType: 'MOUSE_MOVE',
			callBack: e => {
				const { longitude,latitude,height } = e.mapPoint;
				// this.vue.coord.lon = `${FilterNullValue(longitude, 4) || '--'}°`
				// this.vue.coord.lat = `${FilterNullValue(latitude, 4) || '--'}°`
			}
		})
		return this;
	},
	goView({ longitude,latitude,height = 150000 } = {}) { //view跳转
		this.viewer.goTo({
			center: [longitude, latitude, height],
			heading: 0,
			pitch: -90,
			roll: 0
		})
	},
	aggregation(data, level) {	//聚合
		this.map.findLayerById(`aggregaGraphicsLayer${level}`) && this.map.remove(this.map.findLayerById(`aggregaGraphicsLayer${level}`))
		this[`aggregaGraphicsLayer${level}`] = new GraphicsLayer({
			id: 'aggregaGraphicsLayer'+level, 
			viewer: this.viewer
		})
		this.map.add(this[`aggregaGraphicsLayer${level}`]);
		if(level!=1) this[`aggregaGraphicsLayer${level}`].show = false;
		if (data.length != 0) {
			data.forEach(item => {
				let point = [];
				if(item.point) point = item.point.split(' ');
				this.polymerize(item.projectCount, Number(point[0]) + 0.001 || 1, Number(point[1]) + 0.001 || 1, level);
			})
		}
	},
	removeAggregation() {
		this.map.findLayerById(`aggregaGraphicsLayer1`) && this.map.remove(this.map.findLayerById(`aggregaGraphicsLayer1`))
		this.map.findLayerById(`aggregaGraphicsLayer2`) && this.map.remove(this.map.findLayerById(`aggregaGraphicsLayer2`))
		this.map.findLayerById(`aggregaGraphicsLayer3`) && this.map.remove(this.map.findLayerById(`aggregaGraphicsLayer3`))
	},
	polymerize(num=0, lon, lat, level) {
		switch(level) {
			case 1:
				when(new PicStyleSymbol().fromText(num, num < 1000 ? '48' : '60', '#f28cb1', 'circle', num < 1000 ? .8 : .6, 3, 'transparent'), (baseImg) => {
					let outonGraphic = new Graphic({
						geometry: {
							type: 'point',
							longitude: lon,
							latitude: lat,
							height: 30
						},
						symbol: {
							type: 'picture-marker',
							height: num < 1000 ? 45 : 50,
							width: num < 1000 ? 45 : 50,
							url: baseImg,
							heightReference: HeightReference.RELATIVE_TO_GROUND,
							verticalOrigin: VerticalOrigin.BOTTOM, // 添加鼠标点击属性后解决栽点下陷问题
							// scaleByDistance: new NearFarScalar(750000, 0, 760001, 1)
						}
					})
					this[`aggregaGraphicsLayer${level}`].add(outonGraphic);
				})
			break;
			case 2:
				when(new PicStyleSymbol().fromText(num, num < 1000 ? '48' : '60', '#f1f075', 'circle', num < 1000 ? .8 : .6, 3, 'transparent'), (baseImg) => {
					let outonGraphic = new Graphic({
						geometry: {
							type: 'point',
							longitude: lon,
							latitude: lat,
							height: 20
						},
						symbol: {
							type: 'picture-marker',
							height: num < 1000 ? 35 : 40,
							width: num < 1000 ? 35 : 40,
							url: baseImg,
							heightReference: HeightReference.RELATIVE_TO_GROUND,
							verticalOrigin: VerticalOrigin.BOTTOM, // 添加鼠标点击属性后解决栽点下陷问题
							// scaleByDistance: new NearFarScalar(200000, 0, 210001, 1)
						}
					})
					this[`aggregaGraphicsLayer${level}`].add(outonGraphic);
				})
			break;
			case 3:
				when(new PicStyleSymbol().fromText(num, num < 1000 ? '48' : '60', '#51bbd6', 'circle', num < 1000 ? .8 : .6, 3, 'transparent'), (baseImg) => {
					let outonGraphic = new Graphic({
						geometry: {
							type: 'point',
							longitude: lon,
							latitude: lat,
							height: 10
						},
						symbol: {
							type: 'picture-marker',
							height: num < 1000 ? 30 : 35,
							width: num < 1000 ? 30 : 35,
							url: baseImg,
							heightReference: HeightReference.RELATIVE_TO_GROUND,
							verticalOrigin: VerticalOrigin.BOTTOM, // 添加鼠标点击属性后解决栽点下陷问题
							scaleByDistance: new NearFarScalar(30000, 0, 30001, 1)
						}
					})
					this[`aggregaGraphicsLayer${level}`].add(outonGraphic);
				})
			break;
		}
		
	},
	addPointList({ data, type, action}) {	//地图载点
		this.map.findLayerById(type + 'pointGraphicsLayer') && this.map.remove(this.map.findLayerById(type + 'pointGraphicsLayer'))
		// this.pointGraphicsLayer && this.map.remove(this.pointGraphicsLayer);
		this.pointGraphicsLayer = new GraphicsLayer({
			id: type + 'pointGraphicsLayer',
			viewer: this.viewer
		});
		this.map.add(this.pointGraphicsLayer);

		data.forEach(item => {
			this.addPoint(item, type, action);
		});
	},
	removeMapPoints () {
		this.map.findLayerById('projectpointGraphicsLayer') && this.map.remove(this.map.findLayerById('projectpointGraphicsLayer'))
		this.map.findLayerById('maintainpointGraphicsLayer') && this.map.remove(this.map.findLayerById('maintainpointGraphicsLayer'))
		this.map.findLayerById('peoplepointGraphicsLayer') && this.map.remove(this.map.findLayerById('peoplepointGraphicsLayer'))
	},
	addPoint(item, type, action) {
		let point = {
			type: 'point',
			longitude: Number(item.longitude) || 0,
			latitude: Number(item.latitude) || 0,
			height: 35
		}
		let pointSymbol = {}
		if(type == 'people'|| type == 'maintain'){
			pointSymbol = {
				type: 'picture-marker',
				width: 30,
				height: 30,
				url: '',
				// url: require('@/common/images/point.png'),
				heightReference: HeightReference.RELATIVE_TO_GROUND,
				verticalOrigin: VerticalOrigin.BOTTOM, // 添加鼠标点击属性后解决栽点下陷问题
				scaleByDistance: new NearFarScalar(20000, 1, 21001, 0.5)
			}
		}else{
			pointSymbol = {
				type: 'picture-marker',
				width: 30,
				height: 30,
				url: '',
				// url: require('@/common/images/point.png'),
				heightReference: HeightReference.RELATIVE_TO_GROUND,
				verticalOrigin: VerticalOrigin.BOTTOM, // 添加鼠标点击属性后解决栽点下陷问题
				scaleByDistance: new NearFarScalar(20000, 1, 21001, 0)
			}
		}

		let pointGraphic = new Graphic({
			geometry: point,
			symbol: pointSymbol,
			popupTemplate: {
				actions: ()=> {
					action(item);
				}
			}
		});
		this.pointGraphicsLayer.add(pointGraphic);
	},
}
